package com.lanlengran.musicplayer.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lanlengran.musicplayer.R;
import com.lanlengran.musicplayer.beans.MusicInfo;
import com.lanlengran.musicplayer.services.PlayService;
import com.lanlengran.musicplayer.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener,AdapterView.OnItemClickListener,Toolbar.OnMenuItemClickListener {
    private List<File> MusicList = new ArrayList<>();
    private List<String> MusicNameList = new ArrayList<>();
    private List<String> RealNameList = new ArrayList<>();
    private ListView mListView;
    private TextView mLodingTitle;
    private TextView mLodingContext;
    private TextView mMusicTitle;
    private TextView mMusicArtist;
    private ImageButton mPausePlay;
    private ImageButton mNextPaly;
    private ImageButton mMusicIcon;
    private View mView;
    private boolean isFind = false;
    private boolean isStart=false;
    private int mLastPosition;
    private PlayService playService;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    if (MusicList.size()== 0){
                        break;
                    }
                    Bundle bundle=msg.getData();
                    int position=bundle.getInt("position");
                    MusicInfo musicInfo=MusicInfo.queryMusic(MusicNameList.get(position),MainActivity.this);
                    mMusicTitle.setText(RealNameList.get(position));
                    if (musicInfo.getArtist()!=null){
                        mMusicArtist.setText(musicInfo.getArtist());
                    }else {
                        mMusicArtist.setText("未知");
                    }
                //   Bitmap bm = BitmapFactory.decodeFile(musicInfo.getAlbum());
                    String albumArt= MusicInfo.getAlbumArt(MainActivity.this,(int)musicInfo.getAlbumId());
                         Log.i("qin:","musicInfo.getAlbum()="+musicInfo.getAlbumId());
                    Bitmap bm = null;
                    if (albumArt == null) {
                        mMusicIcon.setBackgroundResource(R.mipmap.logo);
                        playService.setNoticeInfo(mMusicTitle.getText().toString(),
                                mMusicArtist.getText().toString(),
                                null);
                    } else {
                        bm = BitmapFactory.decodeFile(albumArt);
                        BitmapDrawable bmpDraw = new BitmapDrawable(bm);
                        mMusicIcon.setImageDrawable(bmpDraw);
                        playService.setNoticeInfo(mMusicTitle.getText().toString(),
                                mMusicArtist.getText().toString(),
                                bmpDraw);
                    }
                    playService.setMusicChange(true);
                    break;
                case 1:
                    final ArrayAdapter adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, RealNameList);
                            mListView.setAdapter(adapter);
                            mListView.setVisibility(View.VISIBLE);
                            mLodingTitle.setVisibility(View.INVISIBLE);
                            mLodingContext.setVisibility(View.INVISIBLE);
                            isFind = false;
                    setRemoveRepeatView();
                 //   startPlay();
                    playService.setmMusicList(MusicList);
                    saveShareDate("MusicList",MusicList);
                    break;


            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mView=getLayoutInflater().inflate(R.layout.activity_main,null);
        setContentView(mView);
        initView();
        if (this.isWorked("com.lanlengran.musicplayer.services.PlayService")){
            try{
                Utils.log_i("服务已经启动");
                playService=PlayService.getPlayService();
                isStart=PlayService.getIsStart();
                mPausePlay.setImageResource(R.drawable.playbar_btn_pause);
                Message message=new Message();
                message.what=0;
                Bundle bundle=new Bundle();
                bundle.putInt("position",playService.getPlayPosition());
                message.setData(bundle);
                handler.sendMessage(message);
                mLastPosition=playService.getPlayPosition();
            }catch (Exception e){
                playService=new PlayService();
                PlayService.setPlayService(playService);
                startPlay();
            }

        }else {
            Utils.log_i("服务没有启动");
            playService=new PlayService();
            PlayService.setPlayService(playService);
            startPlay();

        }

        initList();
        initDate();


    }

    private void initDate() {

        new Thread(){
            @Override
            public void run() {
                super.run();
                while(true){
                    if (mLastPosition!=playService.getPlayPosition()){
                        Message message=new Message();
                        message.what=0;
                        Bundle bundle=new Bundle();
                        bundle.putInt("position",playService.getPlayPosition());
                        message.setData(bundle);
                        handler.sendMessage(message);
                        mLastPosition=playService.getPlayPosition();
                    }
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    private boolean isWorked(String s) {
        ActivityManager manager=(ActivityManager)getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> mServiceList = manager.getRunningServices(100);
        for (int i = 0; i < mServiceList.size(); i++) {
            String clasString = mServiceList.get(i).service.getClassName();
            Utils.log_i("clasString="+clasString+"|||||s="+s);
            if (clasString.equals(s)) {
                Utils.log_i("服务已经启动");
                return true;
            }
        }

        return  false;
    }

    private void initView() {
       findViewById(R.id.reflash_btn).setOnClickListener(this);
        mPausePlay = (ImageButton) findViewById(R.id.btn_pause_play);
        mNextPaly = (ImageButton) findViewById(R.id.btn_next_play);
        mListView = (ListView) findViewById(R.id.lisviewt);
        mLodingTitle = (TextView) findViewById(R.id.loding_title_text);
        mLodingContext = (TextView) findViewById(R.id.loding_context_id);
        mMusicTitle= (TextView) findViewById(R.id.notice_music_tile);
        mMusicArtist=(TextView)findViewById(R.id.notice_music_artist);
        mMusicIcon=(ImageButton)findViewById(R.id.music_icon);

        mListView.setOnItemClickListener(this);
        mPausePlay.setOnClickListener(this);
        mNextPaly.setOnClickListener(this);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setTitle(R.string.app_name);
        toolbar.setOnMenuItemClickListener(this);
    }

    private void findMusic(File file) {
        //   Log.i("qin:",file.toString());

        if (file.isFile()) {
            final String fileName = file.getName();
            String lastName = fileName.substring(fileName.length() - 3, fileName.length());
            if (lastName.equals("mp3")||lastName.equals("aac")||lastName.equals("m4a")||lastName.equals("MP3")) {
                MusicList.add(file);
                mLodingContext.post(new Runnable() {
                    @Override
                    public void run() {
                        mLodingContext.setText("已找到：" + fileName);
                    }
                });

            }
        } else {
            try {
                for (File f : file.listFiles()) {
                    if (f.getName().substring(0, 1).equals(".")) {
                        continue;
                    }
                    findMusic(f);
                }

            } catch (Exception e) {
                Log.e("qin:", file.toString());
            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.reflash_btn:
                //  final File file=new File("/storage");
                flashList();
                //      mListView.refreshDrawableState();
                break;
            case R.id.btn_pause_play:
                pauseORplay();
                break;
            case R.id.btn_next_play:
                playService.nextMusic();
                break;
        }
    }

    private void pauseORplay() {
        if (isStart){
            playService.onPause();
            mPausePlay.setImageResource(R.drawable.playbar_btn_play);
            isStart=false;
        }else {
            playService.onStart();
            mPausePlay.setImageResource(R.drawable.playbar_btn_pause);
            isStart=true;
        }
    }

    private void stopService() {
     //   if (isStart){
            Intent stopPlay=new Intent(this, PlayService.class);
            stopService(stopPlay);
            playService.onStop();
  //      }
    }
    private void startPlay(){
        if (!isStart){
            Intent startPlay=new Intent(this, playService.getClass());
            startService(startPlay);

        }
    }

    private void setRemoveRepeatView() {
        MusicList= removeRepeat(MusicList);
        MusicNameList=getFileName(MusicList);
        RealNameList=getRealName(MusicNameList);
        final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, RealNameList);
        mListView.setAdapter(adapter);
        //  Log.i("qin:","按钮去除重复");
  //      Log.i("qin:", removeRepeat(MusicList).toString());
    }

    private List<File> removeRepeat(List<File> l) {
        int length=l.size();
        for (int i=0;i<l.size();i++){
            for (int j=l.size()-1;j>i;j--){
        //        Log.i("qin:","i="+i+l.get(i).getName()+"||j="+l.get(j).getName());
     //           Log.i("qin:","length="+length);
                if (l.get(i).getName().equals(l.get(j).getName())){
                    l.set(i,new File("null"));
               //     Log.i("qin:","相等");
                }else{
              //      Log.i("qin:","不相等");
                }
            }
        }
        return  removeNull(l);
    }
    private List<File> removeNull(List<File> l){
        for (int i=0;i<l.size();i++){
           if (l.get(i).getName().equals("null")){
               l.remove(i);
               l= removeNull(l);
               return l;
           }
        }
        return l;
    }
    private void initList(){
        MusicList=readShareDate("MusicList",MusicList);
        if (MusicList.size()!=0){
            Utils.toastShort(this,"读取到已存储列表");
            MusicNameList=getFileName(MusicList);
            RealNameList=getRealName(MusicNameList);
            //    startPlay();
            playService.setmMusicList(MusicList);
            final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, RealNameList);
            mListView.setAdapter(adapter);
        }else{
            flashList();
        }
    }
    private void flashList() {
        if (isFind) {
            Toast.makeText(this, "已经在查找了，请稍等哦！", Toast.LENGTH_SHORT).show();
            return;
        } else {
            isFind = true;
        }

            MusicList.clear();
            mLodingTitle.setVisibility(View.VISIBLE);
            mLodingContext.setVisibility(View.VISIBLE);
            mListView.setVisibility(View.INVISIBLE);
            mLodingContext.setText("正在查找");
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    setAdapter();
                }
            }.start();



    }

    private List readShareDate(String name,List<File> list) {
        SharedPreferences preferences=getSharedPreferences(name,MODE_PRIVATE);
        int size=preferences.getInt("size",0);
        for (int i=0;i<size;i++){
            list.add(new File(preferences.getString(""+i,null)));
            Utils.log_i("读取了："+list.get(i).getName());
        }
        return list;
    }
    private void saveShareDate(String name, List<File> list){
        SharedPreferences.Editor editor=getSharedPreferences(name,MODE_PRIVATE).edit();
        editor.putInt("size",list.size());
        for (int i=0;i<list.size();i++){
            editor.putString(""+i,list.get(i).getPath());
            Utils.log_i("保存了："+list.get(i).getName());
        }
        editor.commit();
    }

    private void setAdapter() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    0);
        }
        final File file = new File("/storage");
        final File file2 = new File("/sdcard");
        final File file3 = new File(Environment.getExternalStorageDirectory().getPath());
        try {
            findMusic(file);
            MusicNameList=getFileName(MusicList);
            RealNameList=getRealName(MusicNameList);
            if (MusicList.size()==0){
                findMusic(file2);
                MusicNameList=getFileName(MusicList);
                RealNameList=getRealName(MusicNameList);
                if (MusicList.size()==0){
                    findMusic(file3);
                    MusicNameList=getFileName(MusicList);
                    RealNameList=getRealName(MusicNameList);
                    if (MusicList.size()==0){
                        mLodingContext.setText("很抱歉没有找到任何mp3文件!");
                        isFind = false;
                        return;
                    }
                }
            }
        } catch (Exception e) {
         //   findMusic(Environment.getExternalStorageDirectory());
        }

//        MusicNameList=getFileName(MusicList);
//        if (MusicList.size()==0){
//            mLodingContext.setText("很抱歉没有找到任何mp3文件!");
//            isFind = false;
//            return;
//        }
//        final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, MusicNameList);
        Message message=new Message();
        message.what=1;
        handler.sendMessage(message);
//        mListView.post(new Runnable() {
//            @Override
//            public void run() {
//                mListView.setAdapter(adapter);
//                mListView.setVisibility(View.VISIBLE);
//                mLodingTitle.setVisibility(View.INVISIBLE);
//                mLodingContext.setVisibility(View.INVISIBLE);
//                isFind = false;
//            }
//        });
//        setRemoveRepeatView();

    }

    /**
     * 通过File获得文件的文件名
     * @param l 包含file文件的列表
     * @return 包含对应的文件名的列表
     */
    private List<String> getFileName(List<File> l) {
        List<String> list=new ArrayList<>();
        for (File f : l) {
            list.add(f.getName());
        //    Log.i("qin:","歌曲为"+f.getName());
        }
        return  list;
    }

    /**
     * 通过mp3文件名获得歌曲名称
     * @param l 包含mp3文件名的列表
     * @return  包含对应mp3文件的歌曲名称列表
     */
    private List<String> getRealName(List<String> l) {

        List<String> list=new ArrayList<>();
        for (String f : l) {

            MusicInfo musicInfo=MusicInfo.queryMusic(f,MainActivity.this);
            if (musicInfo==null){
                list.add(f);
                continue;
            }
            if (musicInfo.getTitle()!=null){
                list.add(musicInfo.getTitle());
            }else {
                list.add(f);
            }
        }
        return  list;
    }

    /**
     * 安卓6.0的监听获得权限和没有获得权限，分别做处理
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==0){
            if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
                flashList();
            }else{
                Toast.makeText(this, "文件没有权限，无法查找到歌曲，请允许程序读取权限！", Toast.LENGTH_SHORT).show();
            }

        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        playService.onPlay(position);
        isStart=true;
        mPausePlay.setImageResource(R.drawable.playbar_btn_pause);
    }

    /**
     * 在activity销毁前，将是否播放放值，存入service
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        PlayService.setIsStart(isStart);
        Utils.log_i("被销毁了");
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {

        String msg = "";
        switch (item.getItemId()) {
            case R.id.action_exit:
                finish();
                stopService();
                break;
            case R.id.action_seach:
                msg += "Click share";
                break;
            case R.id.action_flashlist:
                flashList();
                break;
        }

        if(!msg.equals("")) {
            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
        return true;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // 為了讓 Toolbar 的 Menu 有作用，這邊的程式不可以拿掉
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
}
